package com.swak.netty_udp.unicast;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

import com.swak.utils.Fmt;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 * UdpNettyPeer. 
 * 
 * @author 618lf
 */
public class UdpNettyPeer {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap bootstrap;
	Channel channel;
	InetSocketAddress address;

	public UdpNettyPeer(int port) throws InterruptedException {
		bootstrap = new Bootstrap();
		bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
				.option(ChannelOption.SO_RCVBUF, 2048 * 1024).option(ChannelOption.SO_SNDBUF, 1024 * 1024)
				.handler(new ChannelInitializer<NioDatagramChannel>() {
					@Override
					protected void initChannel(NioDatagramChannel ch) {
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast(new UdpPeerHandler());
					}
				});
		this.address = new InetSocketAddress("localhost", port);
		ChannelFuture f = bootstrap.bind(port).sync();
		this.channel = f.channel();
		Fmt.out.println("正在监听......:" + f.channel());
	}

	public void sendMessage(InetSocketAddress address, String message) {
		ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes(StandardCharsets.UTF_8));
		this.channel.writeAndFlush(new DatagramPacket(byteBuf, address));
	}

	public void close() throws InterruptedException {
		this.channel.close().await();
	}

	public static void main(String[] args) throws InterruptedException {
		UdpNettyPeer peerA = new UdpNettyPeer(8088);
		UdpNettyPeer peerB = new UdpNettyPeer(8089);

		Thread.sleep(10000);
		Fmt.out.println("发送数据");
		peerA.sendMessage(peerB.address, "我是B");

		Thread.sleep(10000);
		Fmt.out.println("关闭");
		peerA.close();
		peerB.close();
	}
}
